<template>
  <div class="detail-wrapper">
    <div class="detail-main" v-if="!loading">
      <div class="detail-column">
        <div class="column-title">实验器材基础信息</div>
        <div class="column-content">
          <a-descriptions
            bordered
            :labelStyle="{ width: '120px' }"
            :contentStyle="{ width: '500px' }"
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          >
            <a-descriptions-item label="名称">
              {{ equipmentData?.name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类名称" v-if="equipmentData?.equipment_category_name">
              {{ equipmentData?.equipment_category_name }}
            </a-descriptions-item>
           
            <a-descriptions-item label="入库时间" v-if="equipmentData?.created">
              {{ formatDate(equipmentData?.created) }}
            </a-descriptions-item>
           
            <a-descriptions-item label="状态">
               {{ equipmentData?.enabled ? '启用' : '禁用' }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
      
      <!-- 模型文件区域 - 支持数组 -->
      <div class="detail-column" v-if="equipmentData?.model_files && equipmentData.model_files.length > 0">
        <div class="column-title">预览模型</div>
        <div class="column-content">
          <div class="file-list">
            <div 
              v-for="(modelFile, index) in equipmentData.model_files" 
              :key="index"
              class="file-item"
            >
              <div class="file-info">
                <span class="file-name">{{ modelFile.name || `模型文件${index + 1}` }}</span>
                <span class="file-size" v-if="modelFile.size">{{ formatFileSize(modelFile.size) }}</span>
              </div>
              <a-button 
                :icon="h(DownloadOutlined)" 
                type="primary"
                size="small"
                @click="downloadFile(modelFile.url || modelFile, modelFile.name || `设备模型文件${index + 1}`)"
              >
                下载
              </a-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 兼容旧版单个模型文件 -->
      <div class="detail-column" v-else-if="equipmentData?.model_file">
        <div class="column-title">预览模型</div>
        <div class="column-content">
          <a-button 
            :icon="h(DownloadOutlined)" 
            type="primary"
            @click="downloadFile(equipmentData.model_file, '设备模型文件')"
          >
            下载模型文件
          </a-button>
        </div>
      </div>
      
      <!-- 图片文件区域 - 支持数组 -->
      <div class="detail-column" v-if="equipmentData?.image_files && equipmentData.image_files.length > 0">
        <div class="column-title">预览图片</div>
        <div class="column-content">
          <div class="image-gallery">
            <div 
              v-for="(imageFile, index) in equipmentData.image_files" 
              :key="index"
              class="image-item"
            >
              <div class="image-preview">
                <img 
                  :src="imageFile.url || imageFile" 
                  :alt="imageFile.name || `设备图片${index + 1}`"
                  style="max-width: 200px; max-height: 150px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
                  @error="handleImageError"
                />
              </div>
              <div class="image-info">
                <div class="image-name">{{ imageFile.name || `图片${index + 1}` }}</div>
                <a-button 
                  :icon="h(DownloadOutlined)" 
                  type="primary"
                  size="small"
                  @click="downloadFile(imageFile.url || imageFile, imageFile.name || `设备图片${index + 1}`)"
                >
                  下载
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 兼容旧版单个图片 -->
      <div class="detail-column" v-else-if="equipmentData?.image">
        <div class="column-title">预览图片</div>
        <div class="column-content">
          <div class="image-preview">
            <img 
              :src="equipmentData.image" 
              :alt="equipmentData.name"
              style="max-width: 400px; max-height: 300px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
              @error="handleImageError"
            />
          </div>
          <div style="margin-top: 12px;">
            <a-button 
              :icon="h(DownloadOutlined)" 
              type="primary"
              @click="downloadFile(equipmentData.image, '设备预览图片')"
            >
              下载图片
            </a-button>
          </div>
        </div>
      </div>
      
      <div class="detail-column" v-if="equipmentData?.introduce">
        <div class="column-title">仪器介绍</div>
        <div class="column-text" v-html="equipmentData.introduce">
        </div>
      </div>
      
      <div class="detail-column" v-if="equipmentData?.experiment_content">
        <div class="column-title">实验内容</div>
        <div class="column-text" v-html="equipmentData.experiment_content">
        </div>
      </div>
      
      <div class="detail-column" v-if="configurationParameters.length > 0">
        <div class="column-title">配置参数</div>
        <div class="column-content">
          <a-descriptions
            bordered
            :labelStyle="{ width: '120px' }"
            :contentStyle="{ width: '500px' }"
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          >
            <a-descriptions-item 
              v-for="(param, index) in configurationParameters" 
              :key="index"
              :label="param.configurationName || `配置${index + 1}`"
            >
              {{ param.configurationParameter || '-' }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
      
      <div class="detail-column" v-if="equipmentData?.remark">
        <div class="column-title">备注信息</div>
        <div class="column-text">
          {{ equipmentData.remark }}
        </div>
      </div>
    </div>
    
    <div v-else class="loading-wrapper">
      <a-spin size="large" />
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted } from "vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { DownloadOutlined } from "@ant-design/icons-vue";
import administratorApi from "@/api/administrator";

const route = useRoute();
const loading = ref(true);
const equipmentData = ref(null);
const configurationParameters = ref([]);
const apiResponseInfo = ref(null);

// 初始化数据
onMounted(() => {
  if (route.query.equipment_id) {
    fetchEquipmentDetail();
  } else {
    message.error('缺少必要参数： equipment_id');
    loading.value = false;
  }
});

// 获取设备详情
const fetchEquipmentDetail = async () => {
  try {
    loading.value = true;
    const response = await administratorApi.ExperimentEquipmentFetchModel({
      // experiment_id: route.query.experiment_id,
      equipment_id: route.query.equipment_id
    });
    console.log('获取设备详情响应:', response);

    
    // 适配新的API响应格式
    if (response) {
      equipmentData.value = response;
      
      // 保存API响应信息
      apiResponseInfo.value = response
      
      // 解析配置参数
      if (response?.configuration_parameters) {
        try {
          configurationParameters.value = JSON.parse(response.configuration_parameters);
        } catch (e) {
          console.error('解析配置参数失败:', e);
          configurationParameters.value = [];
        }
      }
      
      console.log('设备详情数据:', equipmentData.value);
      console.log('API响应信息:', apiResponseInfo.value);
      console.log('请求参数:', {
        // experiment_id: route.query.experiment_id,
        equipment_id: route.query.equipment_id
      });
    } else {
      // 处理API错误响应
      const errorMessage = response?.errors || '获取设备详情失败';
      message.error(errorMessage);
      console.error('API响应错误:', response);
      
      // 即使失败也保存响应信息
      if (response) {
        apiResponseInfo.value = {
          statusCode: response.statusCode || 0,
          succeeded: response.succeeded || false,
          timestamp: response.timestamp,
          errors: response.errors,
          extras: response.extras
        };
      }
    }
  } catch (error) {
    console.error('获取设备详情出错:', error);
    message.error('获取设备详情失败');
  } finally {
    loading.value = false;
  }
};

// 下载文件
const downloadFile = (url, filename) => {
  if (!url) {
    message.warning('文件链接不存在');
    return;
  }
  
  try {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('开始下载');
  } catch (error) {
    console.error('下载失败:', error);
    message.error('下载失败');
  }
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.style.display = 'none';
  event.target.parentNode.innerHTML = '<div style="width: 100%; height: 200px; background: #f5f5f5; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #999;">图片加载失败</div>';
};

// 日期格式化函数
const formatDate = (timestamp) => {
  if (!timestamp) return '-';
  try {
    const date = new Date(timestamp * 1000); // 假设时间戳是秒级的
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化失败:', error);
    return '-';
  }
};

// 文件大小格式化函数
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>

<style lang="less" scoped>
.detail-wrapper {
  padding: 16px;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.image-preview {
  text-align: center;
}

.column-text {
  line-height: 1.6;
  color: #666;
}

.detail-column {
  margin-bottom: 24px;
}

.column-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

// 文件列表样式
.file-list {
  .file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    margin-bottom: 8px;
    background: #fafafa;
    border-radius: 8px;
    border: 1px solid #e8e8e8;
    transition: all 0.3s ease;

    &:hover {
      background: #f0f0f0;
      border-color: #d9d9d9;
    }

    .file-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 4px;

      .file-name {
        font-weight: 500;
        color: #333;
        font-size: 14px;
      }

      .file-size {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

// 图片画廊样式
.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;

  .image-item {
    background: #fafafa;
    border-radius: 8px;
    padding: 12px;
    border: 1px solid #e8e8e8;
    transition: all 0.3s ease;

    &:hover {
      background: #f0f0f0;
      border-color: #d9d9d9;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }

    .image-preview {
      text-align: center;
      margin-bottom: 8px;

      img {
        border-radius: 6px;
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    .image-info {
      text-align: center;

      .image-name {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
        word-break: break-all;
      }
    }
  }
}
</style>

